package com.hello.system.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.hello.common.core.web.domain.AjaxResult;
import com.hello.system.domain.dto.WxLoginRequest;
import com.hello.system.domain.dto.WxRegisterRequest;
import com.hello.system.service.IWxUserService;

import java.util.Map;

import lombok.extern.slf4j.Slf4j;

/**
 * 微信用户 控制器
 * 
 * @author hello
 */
@RestController
@RequestMapping("/wx/user")
@Slf4j
public class WxUserController {
    
    @Autowired
    private IWxUserService wxUserService;
    
    /**
     * 微信小程序登录
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody WxLoginRequest loginRequest) {
        return AjaxResult.success(wxUserService.wxLogin(loginRequest));
    }
    
    /**
     * 获取微信用户信息
     */
    @PostMapping("/info")
    public AjaxResult getUserInfo(@RequestBody WxLoginRequest loginRequest) {
        return AjaxResult.success(wxUserService.getWxUserInfo(loginRequest));
    }
    
    /**
     * 专门用于获取微信openid
     */
    @PostMapping("/openid")
    public AjaxResult getWxOpenid(@RequestBody Map<String, String> params) {
        String code = params.get("code");
        if (code == null || code.isEmpty()) {
            log.error("获取微信openid请求中code参数为空");
            return AjaxResult.error("微信code不能为空");
        }
        
        log.info("获取微信openid请求: code={}", code);
        
        Map<String, Object> result = wxUserService.getWxOpenid(code);
        
        if (result.containsKey("error")) {
            return AjaxResult.error(result.get("error").toString());
        }
        
        return AjaxResult.success("获取成功", result);
    }
    
    /**
     * 微信用户注册
     */
    @PostMapping("/register")
    public AjaxResult register(@RequestBody WxRegisterRequest registerRequest) {
        log.info("微信用户注册请求: username={}, codeLength={}", 
                registerRequest.getUsername(), 
                registerRequest.getCode() != null ? registerRequest.getCode().length() : 0);
        
        // 调用注册服务
        Map<String, Object> result = wxUserService.registerWxUser(registerRequest);
        
        if (result.containsKey("error")) {
            return AjaxResult.error(result.get("error").toString());
        }
        
        return AjaxResult.success("注册成功", result);
    }
} 